package com.yxinsur.imc.system.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yxinsur.imc.common.annotation.DataScope;
import com.yxinsur.imc.common.annotation.Tenant;
import com.yxinsur.imc.common.constant.UserConstants;
import com.yxinsur.imc.common.core.domain.TreeSelect;
import com.yxinsur.imc.common.core.domain.entity.SysOrg;
import com.yxinsur.imc.common.core.domain.entity.SysRole;
import com.yxinsur.imc.common.exception.BusinessException;
import com.yxinsur.imc.common.exception.CustomException;
import com.yxinsur.imc.common.rocketMq.entity.PantheonChannelOrganization;
import com.yxinsur.imc.common.utils.SecurityUtils;
import com.yxinsur.imc.common.utils.StringUtils;
import com.yxinsur.imc.system.mapper.SysOrgMapper;
import com.yxinsur.imc.system.mapper.SysRoleMapper;
import com.yxinsur.imc.system.service.ISysOrgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 *
 * @author imc
 */
@Service
@Slf4j
public class SysOrgServiceImpl implements ISysOrgService
{
    @Autowired
    private SysOrgMapper orgMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Value("${pantheon.channelUrl}")
    private String pantheonChannelUrl;

    /**
     * 查询部门及以下ID合集
     * (本身以及下级部门ID的拼接串)
     *
     * @param orgId 部门ID
     * @return 部门信息集合
     */
    @Override
    public String selectChildOrgIds(Long orgId) {
        List<SysOrg> children = this.orgMapper.selectChildrenOrgById(orgId);
        StringBuffer orgIds = new StringBuffer(orgId.toString());
        for (SysOrg org:children) {
            orgIds.append(",").append(org.getOrgId());
        }
        return orgIds.toString();
    }

    /**
     * 查询角色下数据权限部门ID合计
     *
     * @return 部门信息集合
     */
    @Override
    public String selectAuthRoleOrgIds(Long userId,Long tenantId) {
        //查询所有角色
        List<SysRole> roles = this.roleMapper.selectRolePermissionByUserId(userId);
        List<Long> orgIds = new ArrayList<>();
        orgIds.add(-1L);//默认值，防止为空
        for (SysRole role:roles) {
            String rootChildOrgIds = null;
            if(role.getDataScope().equals("1")){//1=所有数据权限
                Long rootOrgId = this.orgMapper.selectRootOrgIdsByTenantId(tenantId);
                rootChildOrgIds = selectChildOrgIds(rootOrgId);
            }else if(role.getDataScope().equals("2")){//2=自定义数据权限
                rootChildOrgIds = this.orgMapper.selectRoleOrgIdsByUserId(userId);
            }
            if(StringUtils.isNotBlank(rootChildOrgIds)){
                orgIds.addAll(Arrays.asList(rootChildOrgIds.split(",")).stream().map(x -> Long.valueOf(x)).collect(Collectors.toList()));
            }
        }
        return org.apache.commons.lang3.StringUtils.strip(orgIds.toString(),"[]").replace(" ", "");
    }

    /**
     * 查询部门管理数据
     *
     * @param org 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(orgAlias = "d")
    @Tenant(alias = "d")
    public List<SysOrg> selectOrgList(SysOrg org)
    {
        return orgMapper.selectOrgList(org,selectAuthRoleOrgIds(SecurityUtils.getLoginUser().getUser().getUserId(),SecurityUtils.getTenantId()));
    }

    /**
     * 构建前端所需要树结构
     *
     * @param orgs 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysOrg> buildOrgTree(List<SysOrg> orgs)
    {
        List<SysOrg> returnList = new ArrayList<SysOrg>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysOrg org : orgs)
        {
            tempList.add(org.getOrgId());
        }
        for (Iterator<SysOrg> iterator = orgs.iterator(); iterator.hasNext();)
        {
            SysOrg org = (SysOrg) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(org.getParentId()))
            {
                recursionFn(orgs, org);
                returnList.add(org);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = orgs;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param orgs 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildOrgTreeSelect(List<SysOrg> orgs)
    {
        List<SysOrg> orgTrees = buildOrgTree(orgs);
        return orgTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Integer> selectOrgListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return orgMapper.selectOrgListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param orgId 部门ID
     * @return 部门信息
     */
    @Override
    public SysOrg selectOrgById(Long orgId)
    {
        return orgMapper.selectOrgById(orgId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param orgId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenOrgById(Long orgId)
    {
        return orgMapper.selectNormalChildrenOrgById(orgId);
    }

    /**
     * 是否存在子节点
     *
     * @param orgId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByOrgId(Long orgId)
    {
        int result = orgMapper.hasChildByOrgId(orgId);
        return result > 0 ? true : false;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param orgId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkOrgExistUser(Long orgId)
    {
        int result = orgMapper.checkOrgExistUser(orgId);
        return result > 0 ? true : false;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param org 部门信息
     * @return 结果
     */
    @Override
    public String checkOrgNameUnique(SysOrg org)
    {
        Long orgId = StringUtils.isNull(org.getOrgId()) ? -1L : org.getOrgId();
        SysOrg info = orgMapper.checkOrgNameUnique(org.getOrgName(), SecurityUtils.getTenantId());
        if (StringUtils.isNotNull(info) && info.getOrgId().longValue() != orgId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存部门信息
     *
     * @param org 部门信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertOrg(SysOrg org)
    {
        SysOrg info = orgMapper.selectOrgById(org.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.ORG_NORMAL.equals(info.getStatus()))
        {
            throw new CustomException("部门停用，不允许新增");
        }
        org.setAncestors(info.getAncestors() + "," + org.getParentId());
        org.setTenantId(SecurityUtils.getTenantId());
        //新增云服机构信息
        //pantheonOrgAdd(org);
        return orgMapper.insertOrg(org);
    }

    private void pantheonOrgAdd(SysOrg org) {
        PantheonChannelOrganization organization = new PantheonChannelOrganization();
        organization.setOrgName(org.getOrgName());
        organization.setOrgRank(org.getAncestors().length()-org.getAncestors().replace(",","").length());
        SysOrg parentOrg = orgMapper.selectOrgById(org.getParentId());
        organization.setParentOrgNo(parentOrg.getOrgGuid());
        organization.setConnactPeople(org.getLeader());
        organization.setOrglSource("2");
        String json = JSON.toJSONString(organization);
        log.debug("新增云服机构信息参数:"+json);
        String returnJson = HttpUtil.post(pantheonChannelUrl+"/ocesnus/channel/org/add",json);
        log.debug("新增云服机构信息返回结果:"+returnJson);
        if(StringUtils.isEmpty(returnJson)){
            throw new BusinessException("新增云服机构信息错误");
        }
        JSONObject result = JSONObject.parseObject(returnJson);
        if(result!=null || result.getIntValue("code")==10000){
            org.setOrgGuid(JSONObject.parseObject(result.getString("data")).getString("orgNo"));
        }else{
            throw new BusinessException(result.get("msg").toString());
        }
    }

    /**
     * 修改保存部门信息
     *
     * @param org 部门信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateOrg(SysOrg org)
    {
        SysOrg newParentOrg = orgMapper.selectOrgById(org.getParentId());
        SysOrg oldOrg = orgMapper.selectOrgById(org.getOrgId());
        if (StringUtils.isNotNull(newParentOrg) && StringUtils.isNotNull(oldOrg))
        {
            String newAncestors = newParentOrg.getAncestors() + "," + newParentOrg.getOrgId();
            String oldAncestors = oldOrg.getAncestors();
            org.setAncestors(newAncestors);
            updateOrgChildren(org.getOrgId(), newAncestors, oldAncestors);
        }
        //修改机构信息
        //pantheonOrgUpdate(org);
        int result = orgMapper.updateOrg(org);
        if (UserConstants.ORG_NORMAL.equals(org.getStatus()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentOrgStatus(org);
        }
        return result;
    }

    private void pantheonOrgUpdate(SysOrg org) {
        PantheonChannelOrganization organization = new PantheonChannelOrganization();
        organization.setOrgName(org.getOrgName());
        organization.setOrgRank(org.getAncestors().length()-org.getAncestors().replace(",","").length());
        SysOrg parentOrg = orgMapper.selectOrgById(org.getParentId());
        organization.setParentOrgNo(parentOrg.getOrgGuid());
        organization.setConnactPeople(org.getLeader());
        organization.setOrglSource("2");
        organization.setOrgNo(orgMapper.selectOrgById(org.getOrgId()).getOrgGuid());
        String json = JSON.toJSONString(organization);
        log.debug("修改云服机构信息参数:"+json);
        String returnJson = HttpUtil.post(pantheonChannelUrl+"/ocesnus/channel/org/update",json);
        log.debug("修改云服机构信息返回结果:"+returnJson);
        if(StringUtils.isEmpty(returnJson)){
            throw new BusinessException("修改云服机构信息错误");
        }
        JSONObject result = JSONObject.parseObject(returnJson);
        if(result==null || result.getIntValue("code")!=10000){
            throw new BusinessException("修改云服机构信息错误");
        }
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param org 当前部门
     */
    private void updateParentOrgStatus(SysOrg org)
    {
        String updateBy = org.getUpdateBy();
        org = orgMapper.selectOrgById(org.getOrgId());
        org.setUpdateBy(updateBy);
        orgMapper.updateOrgStatus(org);
    }

    /**
     * 修改子元素关系
     *
     * @param orgId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateOrgChildren(Long orgId, String newAncestors, String oldAncestors)
    {
        List<SysOrg> children = orgMapper.selectChildrenOrgById(orgId);
        for (SysOrg child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            orgMapper.updateOrgChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param orgId 部门ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOrgById(Long orgId)
    {
        pantheonOrgRemove(orgId);
        return orgMapper.deleteOrgById(orgId);
    }

    /**
     * 删除云服机构信息
     * @param orgId
     */
    private void pantheonOrgRemove(Long orgId) {
        SysOrg sysOrg = orgMapper.selectOrgById(orgId);
        PantheonChannelOrganization org = new PantheonChannelOrganization();
        org.setOrgNo(sysOrg.getOrgGuid());
        String json = JSON.toJSONString(org);
        log.debug("删除云服机构信息参数:"+json);
        String returnJson = HttpUtil.post(pantheonChannelUrl+"/ocesnus/channel/org/remove",json);
        log.debug("删除云服机构信息返回结果:"+returnJson);
        if(StringUtils.isEmpty(returnJson)){
            throw new BusinessException("删除云服机构信息错误");
        }
        JSONObject result = JSONObject.parseObject(returnJson);
        if(result==null || result.getIntValue("code")!=10000){
            throw new BusinessException("删除云服机构信息错误");
        }
    }

    /**
     * 部门不能超过三级
     * @param org
     * @return
     */
    @Override
    public boolean checkOrgGen(SysOrg org) {
        int gen = orgMapper.selectOrgGen(org.getParentId());
        return gen>=3;
    }

    @Override
    @DataScope(orgAlias = "d")
    @Tenant(alias = "d")
    public List<SysOrg> treeselectTenant(SysOrg org) {
        return orgMapper.treeselectTenant(org,SecurityUtils.getTenantId());
    }

    /**
     * 判断机构下是否存在团队
     * @param orgId
     * @return
     */
    @Override
    public boolean checkOrgExistTeam(Long orgId) {
        int result = orgMapper.checkOrgExistTeam(orgId);
        return result > 0;
    }

    @Override
    public int addPantheon(List<PantheonChannelOrganization> organizations) {
        int count =0;
        for (PantheonChannelOrganization organization : organizations) {

            SysOrg sysOrg = new SysOrg();
            sysOrg.setOrgName(organization.getOrgName());
            sysOrg.setOrgGuid(organization.getOrgNo());
            //父及机构编码获得orgid
            SysOrg parentOrg = orgMapper.selectOrgByGuid(organization.getParentOrgNo());
            sysOrg.setParentId(parentOrg.getOrgId());
            sysOrg.setAncestors(parentOrg.getAncestors()+","+parentOrg.getOrgId());
            sysOrg.setOrderNum("1");
            sysOrg.setLeader(organization.getConnactPeople());
            sysOrg.setPhone(organization.getMobile());
            sysOrg.setStatus("0");
            sysOrg.setTenantId(parentOrg.getTenantId());
            count += orgMapper.insertOrg(sysOrg);
        }
        return count;
    }

    @Override
    public int updatePantheon(List<PantheonChannelOrganization> organizations) {
        int count =0;
        for (PantheonChannelOrganization organization : organizations) {
            SysOrg sysOrg = orgMapper.selectOrgByGuid(organization.getOrgNo());
            sysOrg.setOrgName(organization.getOrgName());
            sysOrg.setOrgGuid(organization.getOrgNo());
            //父及机构编码获得orgid
            SysOrg parentOrg = orgMapper.selectOrgByGuid(organization.getParentOrgNo());
            sysOrg.setParentId(parentOrg.getOrgId());
            sysOrg.setOrderNum("1");
            sysOrg.setLeader(organization.getConnactPeople());
            sysOrg.setPhone(organization.getMobile());
            sysOrg.setStatus("0");
            sysOrg.setTenantId(parentOrg.getTenantId());
            count+=updateOrg(sysOrg);
        }
        return count;
    }

    @Override
    public int deletePantheon(List<PantheonChannelOrganization> organizations) {
        int count =0;
        for (PantheonChannelOrganization organization : organizations) {
            SysOrg sysOrg = orgMapper.selectOrgByGuid(organization.getOrgNo());
            if(sysOrg.getParentId()!=0){
                count+=deleteOrgById(sysOrg.getOrgId());
            }
        }
        return count;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysOrg> list, SysOrg t)
    {
        // 得到子节点列表
        List<SysOrg> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysOrg tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysOrg> getChildList(List<SysOrg> list, SysOrg t)
    {
        List<SysOrg> tlist = new ArrayList<SysOrg>();
        Iterator<SysOrg> it = list.iterator();
        while (it.hasNext())
        {
            SysOrg n = (SysOrg) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getOrgId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysOrg> list, SysOrg t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
